/**
 * Project:   warnme-app
 * File:      ReportDialog.java
 * License: 
 *            This file is licensed under GNU General Public License version 3
 *            http://www.gnu.org/licenses/gpl-3.0.txt
 *
 * Copyright: Bartosz Cichecki [ cichecki.bartosz@gmail.com ]
 * Date:      Mar 30, 2014
 */

package dtu.ds.warnme.app.dialog;

import org.apache.http.Header;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;

import com.loopj.android.http.AsyncHttpResponseHandler;

import dtu.ds.warnme.app.R;
import dtu.ds.warnme.app.activity.MainActivity;
import dtu.ds.warnme.app.dialog.listener.ReportDialogListener;
import dtu.ds.warnme.app.model.impl.Event;
import dtu.ds.warnme.app.model.impl.EventType;
import dtu.ds.warnme.app.utils.UiUtilities;
import dtu.ds.warnme.app.ws.client.restful.RestClientHolder;

/**
 * @author Bartosz Cichecki
 * 
 */
public class ReportDialog extends DialogFragment {

	private final static String TAG = "ReportDialog";

	private ReportDialogListener listener;

	private AlertDialog dialog;

	private RadioButton accidentRdBtn;

	private RadioButton policeRdBtn;

	private RadioButton speedCameraRdBtn;

	private EditText noteEditText;

	private View progressView;

	private View formView;

	private EventType getEventType() {
		if (accidentRdBtn.isChecked()) {
			return EventType.ACCIDENT;
		}
		if (policeRdBtn.isChecked()) {
			return EventType.POLICE;
		}
		if (speedCameraRdBtn.isChecked()) {
			return EventType.SPEEDCAMERA;
		}
		throw new IllegalStateException("At least one radio button in the group must be checked!");
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		try {
			listener = (ReportDialogListener) activity;
		} catch (ClassCastException ex) {
			throw new ClassCastException(activity.toString() + " must implement ReportDialogListener");
		}
	}

	@Override
	public Dialog onCreateDialog(Bundle savedInstanceState) {
		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
		View view = getActivity().getLayoutInflater().inflate(R.layout.dialog_report, null);
		builder.setView(view);
		builder.setTitle(R.string.report);
		builder.setPositiveButton(R.string.report, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialogInterface, int which) {
				// Nothing do to here
			}
		});

		builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialogInterface, int which) {
				// Nothing do to here
			}
		});

		progressView = view.findViewById(R.id.dialog_report_progress);
		formView = view.findViewById(R.id.dialog_report_form);

		accidentRdBtn = (RadioButton) view.findViewById(R.id.dialog_report_form_radio_button_event_type_accident);
		policeRdBtn = (RadioButton) view.findViewById(R.id.dialog_report_form_radio_button_event_type_police);
		speedCameraRdBtn = (RadioButton) view.findViewById(R.id.dialog_report_form_radio_button_event_type_speed_camera);
		noteEditText = (EditText) view.findViewById(R.id.dialog_report_form_edit_text_note);

		dialog = builder.create();

		dialog.setOnShowListener(new DialogInterface.OnShowListener() {

			@Override
			public void onShow(DialogInterface dialogInterface) {

				final Button positiveButton = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
				positiveButton.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						String note = noteEditText.getText().toString();
						Location location = (Location) getArguments().get(MainActivity.KEY_CURRENT_LOCATION);

						Event event = new Event();
						event.setEventType(getEventType());
						event.setLatitude(location.getLatitude());
						event.setLongitude(location.getLongitude());
						event.setBearing((180 + location.getBearing()) % 360);
						event.setNote(note);

						RestClientHolder.getRestClient().addEvent(dialog.getContext(), event, new AsyncHttpResponseHandler() {

							@Override
							public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
								Log.e(TAG, "Reporting failed. [statusCode = " + statusCode + ", error=" + error + "]");
								listener.onReportFailed();

								Toast.makeText(dialog.getContext(), R.string.report_failed, Toast.LENGTH_LONG).show();
							}

							@Override
							public void onFinish() {
								positiveButton.setEnabled(true);
								UiUtilities.fadeInFadeOut(formView, progressView);
							}

							@Override
							public void onStart() {
								positiveButton.setEnabled(false);
								UiUtilities.fadeInFadeOut(progressView, formView);
							}

							@Override
							public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
								Log.i(TAG, "Reporting successful. [statusCode = " + statusCode + "]");
								dialog.dismiss();

								listener.onReportSuccessful();
							}

						});

					}
				});

				final Button negativeButton = dialog.getButton(DialogInterface.BUTTON_NEGATIVE);
				negativeButton.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						RestClientHolder.getRestClient().cancelRequests(dialog.getOwnerActivity(), true);
						dialog.dismiss();
						listener.onAbort();
					}
				});

			}
		});

		return dialog;
	}

	@Override
	public void onDismiss(DialogInterface dialogInterface) {
		super.onDismiss(dialog);

		RestClientHolder.getRestClient().cancelRequests(dialog.getContext(), true);
	}

}
